package com.hiray.util

import android.app.Activity
import android.app.Application
import android.os.Bundle
import io.reactivex.subjects.PublishSubject

class AppLifecycle {

    val lifecycleSubject = PublishSubject.create<LifecycleEvent>()

    fun bindLifecycle(app: Application) {
        app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityPaused(activity: Activity) {
                lifecycleSubject.onNext(LifecycleEvent.pause(activity::class.java.canonicalName))

            }

            override fun onActivityResumed(activity: Activity) {
                lifecycleSubject.onNext(LifecycleEvent.resume(activity::class.java.canonicalName))

            }

            override fun onActivityStarted(activity: Activity) {
                lifecycleSubject.onNext(LifecycleEvent.start(activity::class.java.canonicalName))

            }

            override fun onActivityDestroyed(activity: Activity) {
                lifecycleSubject.onNext(LifecycleEvent.destroy(activity::class.java.canonicalName))

            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {
                lifecycleSubject.onNext(LifecycleEvent.save(activity::class.java.canonicalName))

            }

            override fun onActivityStopped(activity: Activity) {
                lifecycleSubject.onNext(LifecycleEvent.stop(activity::class.java.canonicalName))

            }

            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                lifecycleSubject.onNext(LifecycleEvent.create(activity::class.java.canonicalName))

            }

        })
    }
}

class LifecycleEvent constructor(var hostName: String, var lifecycle: ActivityLifecycleEvent) {
    companion object {
        fun start(hostName: String): LifecycleEvent {
            return LifecycleEvent(hostName, ActivityLifecycleEvent.START)
        }

        fun create(hostName: String): LifecycleEvent {
            return LifecycleEvent(hostName, ActivityLifecycleEvent.CREATE)
        }

        fun resume(hostName: String): LifecycleEvent {
            return LifecycleEvent(hostName, ActivityLifecycleEvent.RESUME)
        }

        fun pause(hostName: String): LifecycleEvent {
            return LifecycleEvent(hostName, ActivityLifecycleEvent.PAUSE)
        }

        fun stop(hostName: String): LifecycleEvent {
            return LifecycleEvent(hostName, ActivityLifecycleEvent.STOP)
        }

        fun destroy(hostName: String): LifecycleEvent {
            return LifecycleEvent(hostName, ActivityLifecycleEvent.DESTROY)
        }

        fun save(hostName: String): LifecycleEvent {
            return LifecycleEvent(hostName, ActivityLifecycleEvent.SAVE)
        }
    }
}


enum class ActivityLifecycleEvent {
    START,
    CREATE,
    RESUME,
    PAUSE,
    STOP,
    DESTROY,
    SAVE//onSaveInstanceState
}